package com.example.easytts.controller

import com.example.easytts.service.VideoGenerationService
import com.example.easytts.service.UserService
import org.slf4j.LoggerFactory
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import jakarta.servlet.http.HttpServletRequest
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper

@RestController
@RequestMapping("/api/video")
class VideoController(
    private val videoGenerationService: VideoGenerationService,
    private val userService: UserService
) {
    private val logger = LoggerFactory.getLogger(VideoController::class.java)
    private val objectMapper = jacksonObjectMapper()

    data class VideoGenerateRequest(
        // 使用Map来接收所有前端发送的数据，这样更灵活
        val data: String? = null // 兼容旧格式
    )

    data class VideoGenerateResponse(
        val taskId: String,
        val message: String = "任务已创建，正在后台处理"
    )

    data class TaskStatusResponse(
        val taskId: String,
        val status: String,
        val resultUrl: String? = null,
        val errorMessage: String? = null,
        val createdAt: String,
        val updatedAt: String,
        val subtitleContent: String? = null
    )
    
    data class VideoUploadResponse(
        val taskId: String,
        val message: String = "视频已上传，正在解析字幕"
    )

    /**
     * 创建视频生成任务
     */
    @PostMapping("/generate")
    fun generateVideo(
        @RequestBody requestBody: String,
        @RequestHeader(value = "Authorization", required = false) authHeader: String?,
        servletRequest: HttpServletRequest
    ): ResponseEntity<Any> {
        try {
            // 验证请求数据不为空
            if (requestBody.isBlank()) {
                return ResponseEntity.badRequest().body(mapOf(
                    "code" to 400,
                    "message" to "请求数据不能为空"
                ))
            }

            logger.info("创建视频生成任务: requestBody: $requestBody")

            // 获取用户ID（如果已登录）
            val userId = authHeader?.let { userService.getUserIdFromToken(it) }
            
            // 创建视频生成任务
            val taskId = videoGenerationService.createVideoTask(requestBody, userId)
            
            logger.info("创建视频生成任务: $taskId, 用户ID: $userId")
            
            return ResponseEntity.ok(VideoGenerateResponse(
                taskId = taskId,
                message = "视频生成任务已创建，正在后台处理"
            ))
            
        } catch (e: Exception) {
            logger.error("创建视频生成任务失败", e)
            return ResponseEntity.status(500).body(mapOf(
                "code" to 500,
                "message" to "服务器内部错误: ${e.message}"
            ))
        }
    }

    /**
     * 查询任务状态
     */
    @GetMapping("/task/{taskId}")
    fun getTaskStatus(@PathVariable taskId: String): ResponseEntity<Any> {
        try {
            val task = videoGenerationService.getTaskStatus(taskId)
            
            if (task == null) {
                return ResponseEntity.status(404).body(mapOf(
                    "code" to 404,
                    "message" to "任务不存在"
                ))
            }
            
            val response = TaskStatusResponse(
                taskId = task.taskId,
                status = task.status,
                resultUrl = task.resultUrl,
                errorMessage = task.errorMessage,
                createdAt = task.createdAt.toString(),
                updatedAt = task.updatedAt.toString(),
                subtitleContent = if (task.status == "COMPLETED") task.errorMessage else null // 临时使用errorMessage字段存储字幕内容
            )
            
            return ResponseEntity.ok(mapOf(
                "code" to 200,
                "message" to "success",
                "data" to response
            ))
            
        } catch (e: Exception) {
            logger.error("查询任务状态失败: $taskId", e)
            return ResponseEntity.badRequest().body(mapOf(
                "code" to 400,
                "message" to "查询任务状态失败: ${e.message}"
            ))
        }
    }

    /**
     * 获取用户的任务列表
     */
    @GetMapping("/tasks")
    fun getUserTasks(
        @RequestHeader(value = "Authorization", required = false) authHeader: String?
    ): ResponseEntity<Any> {
        try {
            val userId = authHeader?.let { userService.getUserIdFromToken(it) }
            
            if (userId == null) {
                return ResponseEntity.status(401).body(mapOf(
                    "code" to 401,
                    "message" to "需要登录"
                ))
            }
            
            val tasks = videoGenerationService.getUserTasks(userId)
            val taskResponses = tasks.map { task ->
                TaskStatusResponse(
                    taskId = task.taskId,
                    status = task.status,
                    resultUrl = task.resultUrl,
                    errorMessage = task.errorMessage,
                    createdAt = task.createdAt.toString(),
                    updatedAt = task.updatedAt.toString(),
                    subtitleContent = if (task.status == "COMPLETED") task.errorMessage else null // 临时使用errorMessage字段存储字幕内容
                )
            }
            
            return ResponseEntity.ok(mapOf(
                "code" to 200,
                "message" to "success",
                "data" to taskResponses,
                "total" to taskResponses.size
            ))
            
        } catch (e: Exception) {
            logger.error("获取用户任务列表失败", e)
            return ResponseEntity.badRequest().body(mapOf(
                "code" to 400,
                "message" to "获取任务列表失败: ${e.message}"
            ))
        }
    }

    /**
     * 上传视频并同步解析字幕
     */
    @PostMapping("/upload")
    fun uploadVideo(
        @RequestParam file: MultipartFile,
        @RequestHeader(value = "Authorization", required = false) authHeader: String?,
        servletRequest: HttpServletRequest
    ): ResponseEntity<Any> {
        try {
            // 验证文件不为空
            if (file.isEmpty) {
                return ResponseEntity.badRequest().body(mapOf(
                    "code" to 400,
                    "message" to "视频文件不能为空"
                ))
            }
            
            // 验证文件类型
            val filename = file.originalFilename ?: ""
            val ext = filename.substringAfterLast('.', "").lowercase()
            val allowedExtensions = listOf("mp4", "avi", "mov", "wmv", "flv", "mkv")
            
            if (ext !in allowedExtensions) {
                return ResponseEntity.badRequest().body(mapOf(
                    "code" to 400,
                    "message" to "不支持的视频格式，请上传 ${allowedExtensions.joinToString(", ")} 格式的视频"
                ))
            }
            
            // 获取用户ID（如果已登录）
            val userId = authHeader?.let { userService.getUserIdFromToken(it) }
            
            // 同步处理视频上传并解析字幕
            val result = videoGenerationService.processVideoUpload(file, userId)
            
            // 从result中获取taskId，用于日志记录
            val taskId = (result["data"] as? Map<*, *>)?.get("taskId")?.toString() ?: ""
            logger.info("视频上传成功，字幕解析完成: $taskId, 用户ID: $userId")
            
            // 直接返回服务层的结果，包含data字段
            return ResponseEntity.ok(result)
            
        } catch (e: Exception) {
            logger.error("视频上传或字幕解析失败", e)
            return ResponseEntity.status(500).body(mapOf(
                "code" to 500,
                "success" to false,
                "message" to "服务器内部错误: ${e.message}"
            ))
        }
    }
    
    /**
     * 测试接口 - 检查服务状态
     */
    @GetMapping("/test")
    fun testService(): ResponseEntity<Any> {
        return ResponseEntity.ok(mapOf(
            "code" to 200,
            "message" to "视频生成服务正常运行",
            "timestamp" to System.currentTimeMillis()
        ))
    }

    /**
     * 删除视频生成任务
     */
    @DeleteMapping("/task/{taskId}")
    fun deleteTask(
        @PathVariable taskId: String,
        @RequestHeader(value = "Authorization", required = false) authHeader: String?
    ): ResponseEntity<Any> {
        try {
            // 获取任务信息
            val task = videoGenerationService.getTaskStatus(taskId)
            
            if (task == null) {
                return ResponseEntity.status(404).body(mapOf(
                    "code" to 404,
                    "message" to "任务不存在"
                ))
            }
            
            // 检查权限：只有任务创建者或管理员可以删除任务
            val userId = authHeader?.let { userService.getUserIdFromToken(it) }
            if (userId == null) {
                return ResponseEntity.status(401).body(mapOf(
                    "code" to 401,
                    "message" to "需要登录才能删除任务"
                ))
            }
            
            // 检查是否是任务创建者（如果任务有关联用户）
            if (task.userId != null && task.userId != userId) {
                return ResponseEntity.status(403).body(mapOf(
                    "code" to 403,
                    "message" to "只能删除自己创建的任务"
                ))
            }
            
            // 删除任务
            val success = videoGenerationService.deleteTask(taskId)
            
            if (success) {
                logger.info("删除视频生成任务: $taskId, 用户ID: $userId")
                return ResponseEntity.ok(mapOf(
                    "code" to 200,
                    "message" to "任务删除成功",
                    "taskId" to taskId
                ))
            } else {
                return ResponseEntity.status(500).body(mapOf(
                    "code" to 500,
                    "message" to "删除任务失败"
                ))
            }
            
        } catch (e: Exception) {
            logger.error("删除任务失败: $taskId", e)
            return ResponseEntity.status(500).body(mapOf(
                "code" to 500,
                "message" to "删除任务失败: ${e.message}"
            ))
        }
    }
}
